
# Create a web server
resource "alicloud_instance" "web" {
  image_id              = var.image_id
  internet_charge_type  = "PayByBandwidth"

  instance_type        = var.instance_type
  system_disk_category = "cloud_efficiency"
  security_groups      = alicloud_security_group.group.*.id
  instance_name        = var.host_name
  host_name            = var.host_name
  vswitch_id           = alicloud_vswitch.vsw.id
  tags                 = {
    from = "forrest"
  }

  internet_max_bandwidth_out = 0
}

// Import an existing public key to build a alicloud key pair
resource "alicloud_key_pair" "publickey" {
  key_name   = "forrest-rsa"
  public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAv1VfnAOpnLS2N47xVrtQ9hcsBhZBAWNHFhVkZW651KTfAgXIYyPlMy0ce/Hqziv9ZI3SYa7vn7K3GiIVVCZGGvQz7mAnCXCUEbFnkOpojdbCCoSiYEagrTdlpGwvx7zN8C0tZiOapeUgJLDeMCg38JHGf0pFFXOScVRsiRJYTtQMlRdbpbgzhwiOze26cVLv2VYl4QJ6RcZSz2hcHzub2S2VIy0w8OBMMUYiY24SU3I6ONLAa9CoelN1h3/bH8n1ioNkM0BvHFV//tvrkp1gK6B3PHhWH0RYRfJYe0dNEA7ajaCkU4J/umnswgSp5hv2qW654CAvg5YyGygVXh7VQQ== yantao@yantao0527.me"

}

resource "alicloud_key_pair_attachment" "attachment" {
  key_name     = alicloud_key_pair.publickey.id
  instance_ids = [ alicloud_instance.web.id ]
}

resource "alicloud_eip_association" "eip_asso" {
  allocation_id = alicloud_eip.eip.id
  instance_id   = alicloud_instance.web.id
}

resource "alicloud_dns_record" "record" {
  name        = var.domain
  host_record = var.host_name
  type        = "A"
  value       = alicloud_eip.eip.ip_address
}


data "template_file" "inventory" {
  template   = "${file("k8s.tpl")}"
  depends_on = [ alicloud_instance.web ]

  vars       = {
    host_ip = alicloud_eip.eip.ip_address
  }
}

resource "local_file" "inventory" {
  content  = data.template_file.inventory.rendered
  filename = "./ansible/hosts_k8s.ini"
}

